package com.haihui.platform.utils;

/**
 * Created by HaiHui on 2017/10/24.
 */
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

public class StringUtil {
    public StringUtil() {
    }

    public static String escape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);

        for(int i = 0; i < src.length(); ++i) {
            char j = src.charAt(i);
            if(!Character.isDigit(j) && !Character.isLowerCase(j) && !Character.isUpperCase(j)) {
                if(j < 256) {
                    tmp.append("%");
                    if(j < 16) {
                        tmp.append("0");
                    }

                    tmp.append(Integer.toString(j, 16));
                } else {
                    tmp.append("%u");
                    tmp.append(Integer.toString(j, 16));
                }
            } else {
                tmp.append(j);
            }
        }

        return tmp.toString();
    }

    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0;
        boolean pos = false;

        while(lastPos < src.length()) {
            int pos1 = src.indexOf("%", lastPos);
            if(pos1 == lastPos) {
                char ch;
                if(src.charAt(pos1 + 1) == 117) {
                    ch = (char)Integer.parseInt(src.substring(pos1 + 2, pos1 + 6), 16);
                    tmp.append(ch);
                    lastPos = pos1 + 6;
                } else {
                    ch = (char)Integer.parseInt(src.substring(pos1 + 1, pos1 + 3), 16);
                    tmp.append(ch);
                    lastPos = pos1 + 3;
                }
            } else if(pos1 == -1) {
                tmp.append(src.substring(lastPos));
                lastPos = src.length();
            } else {
                tmp.append(src.substring(lastPos, pos1));
                lastPos = pos1;
            }
        }

        return tmp.toString();
    }

    public static String trimPrefix(String toTrim, String trimStr) {
        while(toTrim.startsWith(trimStr)) {
            toTrim = toTrim.substring(trimStr.length());
        }

        return toTrim;
    }

    public static String trimSufffix(String toTrim, String trimStr) {
        while(toTrim.endsWith(trimStr)) {
            toTrim = toTrim.substring(0, toTrim.length() - trimStr.length());
        }

        return toTrim;
    }

    public static String trim(String toTrim, String trimStr) {
        return trimSufffix(trimPrefix(toTrim, trimStr), trimStr);
    }

    public static String escapeHtml(String content) {
        return StringEscapeUtils.escapeHtml4(content);
    }

    public static String unescapeHtml(String content) {
        return StringEscapeUtils.unescapeHtml4(content);
    }

    public static boolean isEmpty(String str) {
        return str == null?true:str.trim().equals("");
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static String subString(String str, int len) {
        int strLen = str.length();
        if(strLen < len) {
            return str;
        } else {
            char[] chars = str.toCharArray();
            int cnLen = len * 2;
            String tmp = "";
            int iLen = 0;

            for(int i = 0; i < chars.length; ++i) {
                char iChar = chars[i];
                if(iChar <= 128) {
                    ++iLen;
                } else {
                    iLen += 2;
                }

                if(iLen >= cnLen) {
                    break;
                }

                tmp = tmp + String.valueOf(chars[i]);
            }

            return tmp;
        }
    }

    public static boolean isNumberic(String s) {
        if(StringUtils.isEmpty(s)) {
            return false;
        } else {
            boolean rtn = validByRegex("^[-+]{0,1}\\d*\\.{0,1}\\d+$", s);
            return rtn?true:validByRegex("^0[x|X][\\da-eA-E]+$", s);
        }
    }

    public static boolean isInteger(String s) {
        boolean rtn = validByRegex("^[-+]{0,1}\\d*$", s);
        return rtn;
    }

    public static boolean isEmail(String s) {
        boolean rtn = validByRegex("(\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*)*", s);
        return rtn;
    }

    public static boolean isMobile(String s) {
        boolean rtn = validByRegex("^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$", s);
        return rtn;
    }

    public static boolean isPhone(String s) {
        boolean rtn = validByRegex("(0[0-9]{2,3}\\-)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?", s);
        return rtn;
    }

    public static boolean isZip(String s) {
        boolean rtn = validByRegex("^[0-9]{6}$", s);
        return rtn;
    }

    public static boolean isQq(String s) {
        boolean rtn = validByRegex("^[1-9]\\d{4,9}$", s);
        return rtn;
    }

    public static boolean isIp(String s) {
        boolean rtn = validByRegex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", s);
        return rtn;
    }

    public static boolean isChinese(String s) {
        boolean rtn = validByRegex("^[一-龥]+$", s);
        return rtn;
    }

    public static boolean isChrNum(String s) {
        boolean rtn = validByRegex("^([a-zA-Z0-9]+)$", s);
        return rtn;
    }

    public static boolean validByRegex(String regex, String input) {
        Pattern p = Pattern.compile(regex, 2);
        Matcher regexMatcher = p.matcher(input);
        return regexMatcher.find();
    }

    public static boolean isNumeric(String str) {
        int i = str.length();
        if(i == 0) {
            return false;
        } else {
            do {
                --i;
                if(i < 0) {
                    return true;
                }
            } while(Character.isDigit(str.charAt(i)));

            return false;
        }
    }

    public static String makeFirstLetterUpperCase(String newStr) {
        if(newStr.length() == 0) {
            return newStr;
        } else {
            char[] oneChar = new char[]{newStr.charAt(0)};
            String firstChar = new String(oneChar);
            return firstChar.toUpperCase() + newStr.substring(1);
        }
    }

    public static String makeFirstLetterLowerCase(String newStr) {
        if(newStr.length() == 0) {
            return newStr;
        } else {
            char[] oneChar = new char[]{newStr.charAt(0)};
            String firstChar = new String(oneChar);
            return firstChar.toLowerCase() + newStr.substring(1);
        }
    }

    public static String formatParamMsg(String message, Object[] args) {
        for(int i = 0; i < args.length; ++i) {
            message = message.replace("{" + i + "}", args[i].toString());
        }

        return message;
    }

    public static String formatParamMsg(String message, Map params) {
        if(params == null) {
            return message;
        } else {
            Iterator keyIts = params.keySet().iterator();

            while(keyIts.hasNext()) {
                String key = (String)keyIts.next();
                Object val = params.get(key);
                if(val != null) {
                    message = message.replace("${" + key + "}", val.toString());
                }
            }

            return message;
        }
    }

    public static StringBuilder formatMsg(CharSequence msgWithFormat, boolean autoQuote, Object[] args) {
        int argsLen = args.length;
        boolean markFound = false;
        StringBuilder sb = new StringBuilder(msgWithFormat);
        if(argsLen > 0) {
            for(int sw = 0; sw < argsLen; ++sw) {
                String flag = "%" + (sw + 1);

                for(int idx = sb.indexOf(flag); idx >= 0; idx = sb.indexOf(flag)) {
                    markFound = true;
                    sb.replace(idx, idx + 2, toString(args[sw], autoQuote));
                }
            }

            if(args[argsLen - 1] instanceof Throwable) {
                StringWriter var9 = new StringWriter();
                ((Throwable)args[argsLen - 1]).printStackTrace(new PrintWriter(var9));
                sb.append("\n").append(var9.toString());
            } else if(argsLen == 1 && !markFound) {
                sb.append(args[argsLen - 1].toString());
            }
        }

        return sb;
    }

    public static StringBuilder formatMsg(String msgWithFormat, Object[] args) {
        return formatMsg(new StringBuilder(msgWithFormat), true, args);
    }

    public static String toString(Object obj, boolean autoQuote) {
        StringBuilder sb = new StringBuilder();
        if(obj == null) {
            sb.append("NULL");
        } else if(obj instanceof Object[]) {
            for(int i = 0; i < ((Object[])((Object[])((Object[])obj))).length; ++i) {
                sb.append(((Object[])((Object[])((Object[])obj)))[i]).append(", ");
            }

            if(sb.length() > 0) {
                sb.delete(sb.length() - 2, sb.length());
            }
        } else {
            sb.append(obj.toString());
        }

        if(autoQuote && sb.length() > 0 && (sb.charAt(0) != 91 || sb.charAt(sb.length() - 1) != 93) && (sb.charAt(0) != 123 || sb.charAt(sb.length() - 1) != 125)) {
            sb.insert(0, "[").append("]");
        }

        return sb.toString();
    }

    public static String returnSpace(String str) {
        String space = "";
        if(!str.isEmpty()) {
            String[] path = str.split("\\.");

            for(int i = 0; i < path.length - 1; ++i) {
                space = space + "&nbsp;&emsp;";
            }
        }

        return space;
    }

    public static String getArrayAsString(List<String> arr) {
        if(arr != null && arr.size() != 0) {
            StringBuffer sb = new StringBuffer();

            for(int i = 0; i < arr.size(); ++i) {
                if(i > 0) {
                    sb.append(",");
                }

                sb.append((String)arr.get(i));
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    public static String getArrayAsString(String[] arr) {
        if(arr != null && arr.length != 0) {
            StringBuffer sb = new StringBuffer();

            for(int i = 0; i < arr.length; ++i) {
                if(i > 0) {
                    sb.append(",");
                }

                sb.append(arr[i]);
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    public static String getSetAsString(Set set) {
        if(set != null && set.size() != 0) {
            StringBuffer sb = new StringBuffer();
            int i = 0;

            for(Iterator it = set.iterator(); it.hasNext(); sb.append(it.next().toString())) {
                if(i++ > 0) {
                    sb.append(",");
                }
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    public static String htmlEntityToString(String dataStr) {
        dataStr = dataStr.replace("&apos;", "\'").replace("&quot;", "\"").replace("&gt;", ">").replace("&lt;", "<").replace("&amp;", "&");
        int start = 0;
        boolean end = false;
        StringBuffer buffer = new StringBuffer();

        while(start > -1) {
            byte system = 10;
            if(start == 0) {
                int charStr = dataStr.indexOf("&#");
                if(start != charStr) {
                    start = charStr;
                }

                if(start > 0) {
                    buffer.append(dataStr.substring(0, start));
                }
            }

            int end1 = dataStr.indexOf(";", start + 2);
            String charStr1 = "";
            char length;
            if(end1 != -1) {
                charStr1 = dataStr.substring(start + 2, end1);
                length = charStr1.charAt(0);
                if(length == 120 || length == 88) {
                    system = 16;
                    charStr1 = charStr1.substring(1);
                }
            }

            try {
                length = (char)Integer.parseInt(charStr1, system);
                buffer.append((new Character(length)).toString());
            } catch (NumberFormatException var7) {
                var7.printStackTrace();
            }

            start = dataStr.indexOf("&#", end1);
            if(start - end1 > 1) {
                buffer.append(dataStr.substring(end1 + 1, start));
            }

            if(start == -1) {
                int length1 = dataStr.length();
                if(end1 + 1 != length1) {
                    buffer.append(dataStr.substring(end1 + 1, length1));
                }
            }
        }

        return buffer.toString();
    }

    public static String stringToHtmlEntity(String str) {
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < str.length(); ++i) {
            char c = str.charAt(i);
            switch(c) {
                case '\n':
                    sb.append(c);
                    break;
                case '\"':
                    sb.append("&quot;");
                    break;
                case '&':
                    sb.append("&amp;");
                    break;
                case '\'':
                    sb.append("&apos;");
                    break;
                case '<':
                    sb.append("&lt;");
                    break;
                case '>':
                    sb.append("&gt;");
                    break;
                default:
                    if(c >= 32 && c <= 126) {
                        sb.append(c);
                    } else {
                        sb.append("&#x");
                        sb.append(Integer.toString(c, 16));
                        sb.append(';');
                    }
            }
        }

        return sb.toString();
    }

    public static String convertSpecialCharacterforDB(String str) {
        if(null != str && !"".equals(str)) {
            str = str.replaceAll("\'", "\'\'");
            str = str.replaceAll("\\\\", "\\\\\\\\");
            str = str.replaceAll("%", "\\\\%");
            str = str.replaceAll("_", "\\\\_");
        }

        return str;
    }

    public static void main(String[] args) {
    }

    public static String string2MD5(String inStr) {
        MessageDigest md5 = null;

        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception var8) {
            var8.printStackTrace();
            return "";
        }

        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for(int md5Bytes = 0; md5Bytes < charArray.length; ++md5Bytes) {
            byteArray[md5Bytes] = (byte)charArray[md5Bytes];
        }

        byte[] var9 = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();

        for(int i = 0; i < var9.length; ++i) {
            int val = var9[i] & 255;
            if(val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }

    public static String convertMD5(String inStr) {
        char[] a = inStr.toCharArray();

        for(int s = 0; s < a.length; ++s) {
            a[s] = (char)(a[s] ^ 116);
        }

        String var3 = new String(a);
        return var3;
    }
}
